import moment, {Moment} from 'moment'
import {ResponseError} from '../../../api/ResponseError'

function formatDate(date: Date | string): string {
  if (!date) {
    return '-'
  } else {
    return moment(date).format('DD.MM.YYYY')
  }
}

function formatDateTime(date: Date | string): string {
  if (!date) {
    return '-'
  } else {
    return moment(date).format('DD.MM.YYYY в HH:mm')
  }
}

const uiRegexp = /^\d?\d\.\d?\d\.\d\d\d\d/
const serverRegexp = /^\d\d\d\d\-\d?\d\-\d?\d/
const UI_DATE_FORMAT = 'DD.MM.YYYY'
const SERVER_DATE_FORMAT = 'YYYY-MM-DD'

function throwUnsupportedFormat(date: string) {
  throw new ResponseError(
    409,
    `Неверный формат даты ${date}. Пожалуйста, обратитесь в службу поддержки`,
  )
}

function formatToUI(date: string | Date | undefined): string | undefined {
  if (!date) {
    return undefined
  } else {
    if (typeof date === 'string') {
      if (uiRegexp.test(date)) {
        return date
      } else if (serverRegexp.test(date)) {
        return moment(date, SERVER_DATE_FORMAT).format(UI_DATE_FORMAT)
      } else {
        throwUnsupportedFormat(date)
      }
    } else {
      return moment(date).format(UI_DATE_FORMAT)
    }
  }
}

function formatToServer(date: string | Date | undefined): string | undefined {
  if (!date) {
    return undefined
  } else {
    if (typeof date === 'string') {
      if (serverRegexp.test(date)) {
        return date
      } else if (uiRegexp.test(date)) {
        return moment(date, UI_DATE_FORMAT).format(SERVER_DATE_FORMAT)
      } else {
        throwUnsupportedFormat(date)
      }
    } else {
      return moment(date).format(SERVER_DATE_FORMAT)
    }
  }
}

function toDateFromServer(date: string | undefined): Moment | undefined {
  if (date) {
    if (serverRegexp.test(date)) {
      return moment(date, SERVER_DATE_FORMAT).utc(true)
    } else {
      throwUnsupportedFormat(date)
    }
  } else {
    return undefined
  }
}

function toDateFromUi(date: string | undefined): Moment | undefined {
  if (date) {
    if (uiRegexp.test(date)) {
      return moment(date, UI_DATE_FORMAT).utc(true)
    } else {
      throwUnsupportedFormat(date)
    }
  } else {
    return undefined
  }
}

function getNowTime(): number {
  return new Date().getTime()
}

export {
  formatDate,
  formatDateTime,
  formatToServer,
  formatToUI,
  toDateFromUi,
  toDateFromServer,
  getNowTime,
}
